import Vue from 'vue'

const isNumber = val => typeof val === 'number' && val === val

// 使用 v-decimalsNum="2" 如果为0，默认保留两位
Vue.directive('decimalsNum', {

  inserted: function (el, binding, vnode) {

    // 获取到input元素
    let targetObj = el.firstElementChild

    // 获取指定保留多少位小数
    let pos = binding.value && binding.value !== 0 ? binding.value : 2

    // 监听blur事件
    targetObj.addEventListener('blur', function (event) {

      if (!binding.value) {
        return
      }

      let v = parseFloat(targetObj.value)

      if (isNumber(v)) {

        let pow = Math.pow(10, pos)

        let result = (Math.round(v * pow) / pow).toString()

        targetObj.value = result

        vnode.data.model.callback(result)

      }

    })

  }
})

// directive: 限制input[number]框最大值
Vue.directive('limitMaxNum', {
  bind(el, binding, vnode) {
    if(binding.value === null){
      return;
    }

    let targetNode = el.firstElementChild;
    targetNode.addEventListener('input', (e) => {
      // 非数字的输入值直接忽视
      if (!/\d+/.test(parseFloat(targetNode.value))) {
        targetNode.value = '';
      }
      if (targetNode.value !== '' && targetNode.value > binding.value) {
        // 直接修改targetNode的值并不会触发input事件，故使用dispatchEvent触发；
        let _event = new Event('input', { bubbles: true });
        targetNode.value = binding.value;
        targetNode.dispatchEvent(_event);
      }
    });
  },
});

// directive: 限制input[number]框最小值
Vue.directive('limitMinNum', {
  bind(el, binding) {
    if(binding.value === null){
      return;
    }

    let targetNode = el.firstElementChild;
    targetNode.addEventListener('input', () => {
      if (!/\d+/.test(parseFloat(targetNode.value))) {
        targetNode.value = '';
      }
      if (targetNode.value !== '' && targetNode.value < binding.value) {
        let _event = new Event('input', { bubbles: true });
        targetNode.value = binding.value;
        targetNode.dispatchEvent(_event);
      }
    });
  },
});
